// utils/db.js
export default {
  dbName: 'bpDB',
  dbPath: '_doc/bloodPressure.db',

  // 初始化数据库
  async init() {
    await this.openDB();
    await this.createTable();
  },

  openDB() {
    return new Promise((resolve, reject) => {
      plus.sqlite.openDatabase({
        name: this.dbName,
        path: this.dbPath,
        success: () => resolve(),
        fail: (e) => reject(`数据库打开失败：${JSON.stringify(e)}`)
      });
    });
  },

  createTable() {
    const sql = `CREATE TABLE IF NOT EXISTS blood_pressure (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      high_pressure INTEGER NOT NULL,
      low_pressure INTEGER NOT NULL,
      record_time DATETIME DEFAULT CURRENT_TIMESTAMP
    )`;
    
    return this.executeSQL(sql);
  },

  executeSQL(sql, params = []) {
    return new Promise((resolve, reject) => {
      plus.sqlite.executeSql({
        name: this.dbName,
        sql: sql,
        data: params,
        success: (res) => resolve(res),
        fail: (e) => reject(`SQL执行失败：${JSON.stringify(e)}`)
      });
    });
  },

  selectSQL(sql) {
    return new Promise((resolve) => {
      plus.sqlite.selectSql({
        name: this.dbName,
        sql: sql,
        success: (data) => resolve(data),
        fail: () => resolve([])
      });
    });
  }
}